﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using System;

public abstract class SpriteDragBase : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Action<SpriteDragBase> _onBeginDrag;
    public Action<SpriteDragBase> _onEndDrag;

    public Camera _camera;
    public bool _IsEnableDrag = true;
    public float _dragBreakDistance = 1;
    bool _isDragOver = false;
    bool _onDragging = false;
    Vector3 _lastPos;
    Vector3 _targetPos;
    RaycastHit2D _hit;

    private bool IsCanDrag
    {
        get
        {
            Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
            _hit = Physics2D.GetRayIntersection(ray,1 << LayerMask.NameToLayer("Floor"));
            if (_hit)
            {
                float distance = Vector3.Distance(_hit.point, _lastPos);
                if (distance > _dragBreakDistance)
                {
                    return false;
                }
                else if(_IsEnableDrag)
                {
                    return true;
                }
            }
            return false;
        }
    }

    private void Awake()
    {
        if(_camera == null) _camera = Camera.main;
    }

    private void Update()
    {
        if(_onDragging && IsCanDrag)
            transform.position = Vector3.Lerp(transform.position, _targetPos, 1f);
    }

    public virtual void OnBeginDrag(PointerEventData eventData)
    {
        _onDragging = true;
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        _hit = Physics2D.GetRayIntersection(ray, 1 << LayerMask.NameToLayer("Floor"));
        if(_hit)
            _lastPos = _targetPos = new Vector3(_hit.point.x, _hit.point.y, transform.position.z);

        if (_onBeginDrag != null) _onBeginDrag(this);
    }

    public virtual void OnDrag(PointerEventData eventData)
    {
        if (IsCanDrag)
        {
            _targetPos = new Vector3(_hit.point.x, _hit.point.y, transform.position.z);
            _lastPos = transform.position;
        }
    }

    public virtual void OnEndDrag(PointerEventData eventData)
    {
        _onDragging = false;
        if (_onEndDrag != null) _onEndDrag(this);
    }

}
